package net.alan.modules.controller;

import net.alan.common.utils.Base64;
import net.alan.common.utils.IOUtils;
import net.alan.modules.bean.CustomConfig;
import net.alan.modules.cache.WebContextUtil;
import net.alan.modules.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Controller
@RequestMapping(value = "photo")
public class PhotoController {
    @Autowired
    private IUserService userService;
    @Autowired
    private CustomConfig customConfig;

    @RequestMapping(value = "get/{id}", method = RequestMethod.GET)
    @ResponseBody
    public void getPhoto(@PathVariable("id") Integer id, HttpServletResponse response) {
        if (id == null || id <= 0)
            id = WebContextUtil.getUserId();
        response.setCharacterEncoding("utf-8");
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            String photoPath = customConfig.getPhotoPath() + id + ".jpg";
            if (!new File(photoPath).exists()) {
                File file = ResourceUtils.getFile("classpath:static/images/user_photo.jpg");
                IOUtils.copyStream(file, os);
            } else {
                IOUtils.copyStream(new File(photoPath), os);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.flush();
            } catch (Exception e) {
            }
            IOUtils.closeIO(os);
        }
    }

    @RequestMapping(value = "image/{name}", method = RequestMethod.GET)
    @ResponseBody
    public void getImage(@PathVariable("name") String name, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            String work = customConfig.getWorkPath();
            String fileName = Base64.decodeString(name);
            String filePath = work + fileName;
            IOUtils.copyStream(new File(filePath), os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.flush();
            } catch (Exception e) {
            }
            IOUtils.closeIO(os);
        }
    }

}
